package cn.nio.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class ChatServer {

    private ServerSocketChannel serverSocketChannel;
    private static final int PORT = 9527;
    private Selector selector;

    /**
     * 初始化
     *
     * @throws Exception
     */
    public void initServer() throws Exception {
        selector = Selector.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.register(selector, SelectionKey.OP_READ);
        serverSocketChannel.configureBlocking(false);

    }

    /**
     * 接受/转发客户端消息
     */
    public void receiveClientInfo() throws Exception {

        while (true) {
            int select = selector.select();
            if (select > 0) {
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterators = selectionKeys.iterator();

                while (iterators.hasNext()) {
                    //获取监听 key对象
                    SelectionKey key = iterators.next();
                    //有客户端连接
                    if (key.isAcceptable()) {
                        //获取socketChannel 客户端连接
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        //设置非阻塞
                        socketChannel.configureBlocking(false);
                        //socketChannel 注册到selector 上
                        socketChannel.register(selector, SelectionKey.OP_ACCEPT);
                        //用户上线提醒
                        System.out.println("有用户上线：" + socketChannel.getRemoteAddress());
                    }

                    SocketChannel socketChannel = null;
                    try {
                        //读操作
                        if (key.isReadable()) {
                            socketChannel = (SocketChannel) key.channel();
                            //将数据从通道读取到缓冲区
                            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                            int read = socketChannel.read(byteBuffer);
                            if (read > 0) {
                                String msg = new String(byteBuffer.array());
                                System.out.println("读取到数据:" + msg);
                                //转发消息给其它用户
                                tranceMessage2OtherClient(msg, socketChannel);
                            }
                        }
                    }catch (IOException e){
                        System.out.println("用户下线:"+socketChannel.getRemoteAddress());
                        key.cancel();
                        socketChannel.close();
                    }
                    //删除处理过的key
                    iterators.remove();
                }
            }
        }
    }

    /**
     * 转发消息到其他客户端
     *
     * @param msg
     * @param selfChannel
     */
    private void tranceMessage2OtherClient(String msg, SocketChannel selfChannel) throws Exception {

        Set<SelectionKey> keys = selector.keys();
        for (SelectionKey key : keys) {
            Channel channel = key.channel();
            //发送者不接受消息
            if (channel instanceof SocketChannel && !channel.equals(selfChannel)) {
                SocketChannel targetChannel = (SocketChannel) channel;
                //消息写入到目标通道
                int write = targetChannel.write(ByteBuffer.wrap(msg.getBytes()));
            }
        }
    }
}
